// components/tableItem/tableItem.js
// import http from '../../api/http.js'
import isTool from '../../utils/AKIsTool'
/**
 * form类型type:  
 * 输入框: input
 * 选择框(布尔-是否): boolean
 * 选择框(数组): originPicker
 * 选择框(对象数组): picker
 * 选择框(多选-对象数组): radioPicker
 * 选择框(时间): yearAndMonth / yearAndMonthAndDay
 * 选择框(地区): area
 * 上传附件: uploadFile
 * 多行输入框: textarea
 * 富文本: editor
 * 步进: stepper
 * 
 * 其他: slot-插槽注入
 * 例子: <view slot="verification"></view>
 * js:  {"customTitle":"研发方向","customType":"developmentDirection"}
 */

/**
 * 
 * 基础属性
 * title:       标题
 * type:        类型
 * key:         参数
 * checkType:   检测类型(支持:手机号,价格,数字)
 * isRequired:  是否必填
 * isEdit:      是否可编辑(详情)
 * isHidden:    是否隐藏
 * isColumn:    是否垂直布局
 * ----------------------------------------------------------------------------------
 * ----------------------------------------------------------------------------------
 * 
 * 1.类型: 输入框 input
 ** 属性: 
 *** tips: 提示
 *** inputType: input输入类型
 *** 支持input基础组件属性(例:placeholder)
 * 
 * 例子:
 * {title: '案例详情',type: 'editor',key:'introduction',inputType:'text',placeholder:'请输入',isRequired:'true'}
 * 
 * ----------------------------------------------------------------------------------
 * 2.类型: 选择框(布尔-是否)
 * {"title":"是否全职","type":"boolean","key":"fullTimeJob"}
 * 
 * ----------------------------------------------------------------------------------
 * 3.类型: 选择框(数组) originPicker
 ** 属性:
 *** array: 数据源
 * 
 * 例子:
 * {"title":"人才层次类别","type":"originPicker","key":"talentLevel"}
 * 
 * ----------------------------------------------------------------------------------
 * 4.类型: 选择框(对象数组) picker
 ** 属性:
 *** array: 数据源
 *** rangeKey: 根据对象key获取值
 *** pid: 根据pid获取业务枚举列表
 * 
 * 例子:
 * {"title":"应用行业","type":"picker","key":"applicationIndustry","array":[],"rangeKey":"title","isRequired":true}
 * 根据pid
 * {"title":"需求子类型","type":"picker","key":"subIndustryField","pid":"ad32b860eac64d82b51c73fb8fb8f0a2","rangeKey":"title","array":[],"isRequired":true}
 * 
 * ----------------------------------------------------------------------------------
 * 5.类型: 选择框(多选-对象数组) radioPicker
 ** 属性:
 *** max: 最多选择数量(默认99)
 * 
 * 例子:
 * {"title":"服务领域","type":"radioPicker","key":"serviceField","isRequired":"true","max":5,"array":[],"rangeKey":"title"}
 * 
 * ----------------------------------------------------------------------------------
 * 6.类型: 选择框(时间) yearAndMonth / yearAndMonthAndDay
 ** 年月
 * {"title":"回国时间","type":"yearAndMonth""key":"returnTime",}
 ** 年月日
 * {"title":"回国时间","type":"yearAndMonthAndDay""key":"returnTime",}
 * 
 * ----------------------------------------------------------------------------------
 * 7.类型: 选择框(地区) area
 ** 属性:
 *** level: 选择器层级,region区级(默认)/city市级/province省级/sub-district街道
 * 
 * 例子:
 * {"title":"地区","type":"area","key":"address","level":"city"}
 * 
 * ----------------------------------------------------------------------------------
 * 8.类型: 上传附件 uploadFile
 ** 属性:
 *** accept: 接受的文件类型, 可选值为all media image file video (默认: all)
 *** uploadType: base基础(默认)/singleUrl单文件
 *** tips: 提示
 *** height: 内容高度
 *** maxSize: 文件大小限制，单位为byte(默认:1G)
 *** max: 文件上传数量限制
 *** icon: 上传区域图标，可选值见 van-icon 组件 (默认: plus)
 * 
 * 例子:
 * {"title":"主图视频","key":"videos","type":"uploadFile","maxSize":"31457280","tips":"(建议时长9-30秒，建议视频宽高比16:9，不超过30MB)"}
 * 
 * ----------------------------------------------------------------------------------
 * 9.类型: 多行输入框 textarea
 ** 属性:
 *** inputType: input输入类型
 * 
 * 例子:
 * {"title":"商品详情","key":"details","type":"textarea"} 
 * 
 * ----------------------------------------------------------------------------------
 * 10.类型: 富文本 editor
 * 
 * 例子:
 * {"title":"商品详情","key":"details","type":"editor"}
 * 
 * ----------------------------------------------------------------------------------
 * 11.类型: 步进 stepper
 * 
 * 例子:
 * {"title":"店铺内排序","key":"sort","type":"stepper"}
 * 
 * ----------------------------------------------------------------------------------
 * 12.类型: 插槽
 * html: <view slot="verification"></view>
 * js:  {"customTitle":"研发方向","customType":"verification"}
 * 
 */

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    detail: {
      type: Object,
      value: {},
      observer: function () {}
    },
    // 注入页面-填写内容参数名称
    detailName: {
      type: String,
      value: "detail"
    },
    // 布局项
    formData: {
      type: Array,
      value: [],
      observer: function () {
        setTimeout(() => {
          console.log("1.布局改变 ===============")
          // 初始化
          this.init()
          // 更新: 注入主界面form对象
          this.resetCurrentPagesForm()
        })
      }
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    // detail: {},
    array: [],
    fileList: [],
    dictionary: {},
    componentFormData: [],
    isShowRadioPicker: {}
  },

  options: {
    multipleSlots: true // 在组件定义时的选项中启用多slot支持
  },
  /**
   * 组件的方法列表
   */
  methods: {
    init() {
      console.log("2.触发初始化 ===============")
      const parentTarget = getCurrentPages()[getCurrentPages().length - 1]
      const tableItemId = this.id || 'tableItem'
      this.id = tableItemId
      this.parentTarget = parentTarget
      parentTarget[tableItemId + "Target"] = this

      // 通过ID选中picker数组
      try {
        this.filterArray()
      } catch (err) {
        console.error("form数据处理异常!!", err)
      }

      // 注入页面
      const params = {}
      params[tableItemId + "Target"] = this.data
      parentTarget.setData(params)
      parentTarget[this.id] = this
    },
    // 通过ID选中picker数组
    filterArray() {
      const parentTarget = getCurrentPages()[getCurrentPages().length - 1]
      const formData = this.data.formData
      const parentDetail = parentTarget.data[this.data.detailName] || {}
      for (let item of formData) {
        if (item.type == "picker") {
          for (let pickerIndex in item.array) {
            const pickerItem = item.array[pickerIndex]
            if (pickerItem.id == parentDetail[item.key]) {
              item.seletedIndex = pickerIndex
            }
          }
        } else if (item.type == 'yearAndMonthAndDay') {
          const nowDate = wx.timestampToTime(new Date())
          parentDetail.date = nowDate
          const params = {}
          params[this.data.detailName] = parentDetail
          parentTarget.setData(params)
          // this.setData({
          //   detail: parentDetail
          // })
        }
      }
      this.setData({
        formData
      })
      // console.log('formData', formData)
    },
    // 更新:注入主界面form对象
    resetCurrentPagesForm() {
      const parentTarget = getCurrentPages()[getCurrentPages().length - 1]
      const params = {}
      params[this.id + 'Target'] = this.data
      parentTarget.setData(params)
    },
    // 更新:注入主界面detail数据
    updateDetailForParentPagesTarget(detail) {
      const parentTarget = this.parentTarget
      const params = {}
      params[this.data.detailName] = detail
      this.setData(params)
      parentTarget.setData(params)
    },


    // ============================ 触发方法 ==================================
    //内容输入
    inputData(e) {
      let {
        index,
        range,
        type,
      } = e.currentTarget.dataset
      let tempValue = e.detail.value
      let tempParentTargetValue = null
      let seletedIndex
      // console.log(e)
      switch (type) {
        case 'boolean':
          if (tempValue == 1) {
            tempValue = true
          } else if (tempValue == 0) {
            tempValue = false
          } else {
            tempValue = ''
          }
          break
        case 'originPicker':
          seletedIndex = e.detail.value
          tempValue = range[tempValue]
          break
        case 'picker':
          seletedIndex = e.detail.value
          tempValue = range[tempValue].id || range[tempValue]
          break
        case 'dictionary':
          seletedIndex = e.detail.value
          tempValue = range[tempValue].code
          break
        case 'stepper':
          tempValue = e.detail
          break
        case 'yearAndMonth':
        case 'yearAndMonthAndDay':
          tempParentTargetValue = new Date(tempValue).getTime()
          break
        default:
          break
      }
      const formData = this.data.formData
      // 值
      formData[index].value = tempValue
      seletedIndex && (formData[index].seletedIndex = seletedIndex)

      // 更新父界面的详情对象属性
      this.updateParentTargetDetail(formData[index].key, tempParentTargetValue || tempValue)

      this.setData({
        formData,
      })

      setTimeout(() => {
        // 更新:注入主界面form对象
        this.resetCurrentPagesForm()
      })
      // 触发父控件
      this.triggerEvent("change", {
        index,
        value: tempValue,
        formItem: formData[index],
        type,
      })

      // 判断是否有隐藏项
      this.chekcHidden()
    },
    chekcHidden() {
      const {
        formData
      } = this.data
      formData.forEach(item => {
        if (item.isHidden) {
          item.value = null
        }
      })
      this.setData({
        formData
      })
    },
    // 自定义输入
    customInput(key, value) {
      const formData = this.data.formData
      // 更新父界面的详情对象属性
      this.updateParentTargetDetail(key, value)

      for (let item of formData) {
        if (item.key == key) item.value = value
      }
    },
    afterRead(e) {
      const tempFile = e.detail.file
      let {
        detail
      } = this.data
      const {
        key,
        uploadType
      } = e.currentTarget.dataset;
      // 状态status: uploading表示上传中，failed表示上传失败，done表示上传完成
      const tempFilePathLoading = tempFile.map(item => ({
        ...item,
        status: 'uploading',
        message: '上传中',
        deletable: false // 是否展示删除按钮
      }))
      detail[key] = detail[key] ? [...detail[key], ...tempFilePathLoading] : tempFilePathLoading
      
      this.setData({
        detail
      })
      // 模拟上传完成
      setTimeout(() => {
        // 修改status完成状态done
        if (detail[key]) {
          detail[key].forEach(item => {
            item.status = 'done'
            item.deletable = true
            item.message = ''
          })
          // 更新父页面属性
          this.updateDetailForParentPagesTarget(detail)
          console.log("图片上传演示使用:可根据需求修改[注意1]以下内容", detail)
        }
      },1500)
      return
      // [注意1]: 根据接口使用封装requestUploadFile上传,可根据需求修改上传后的逻辑
      http.requestUploadFile(tempFilePath,
        // ===== 请求成功 ====
        (urls) => {
          wx.hideToast()
          // 清除上传中
          if (detail[key]) {
            detail[key] = detail[key].filter(item => item.status != 'uploading')
          }
          detail[key] = detail[key] ? [...detail[key], ...urls] : urls
          // 更新页面
          const value = uploadType == "singleUrl" ? urls[0] : detail[key]
          this.updateParentTargetDetail(key, value)
        },
        // ===== 请求失败 ====
        (e) => {
          console.error("请求失败", e)
          wx.hideToast()
          // 清除上传中
          if (detail[key]) {
            detail[key] = detail[key].filter(item => item.status != 'uploading')
          }
          // 修改父方法
          this.parentTarget.setData({
            detail
          })
          // 提示错误
          wx.showToast({
            icon: "none",
            title: e.msg,
          })
        })
    },

    updateParentTargetDetail(key, value) {
      const parentTarget = getCurrentPages()[getCurrentPages().length - 1]
      // 更新父界面的详情对象属性
      const detailName = this.data.detailName
      const parentDetail = parentTarget.data[detailName] || {}
      parentDetail[key] = value
      // 创建更新对象
      const parentTargetUpdate = {}
      parentTargetUpdate[detailName] = parentDetail
      // 更新
      parentTarget.setData(parentTargetUpdate)
      // this.setData({
      //   detail: parentDetail
      // })
    },
    check(options = {
      isShowToast: true,
      isThrow: true
    }) {
      let {
        formData,
        isShowToast = true,
        isThrow = true
      } = options
      // 获取所有必填未填项
      const parentTarget = getCurrentPages()[getCurrentPages().length - 1]
      formData = formData || parentTarget.data.formData
      for (let item of formData) {
        const value = parentTarget.data.detail[item.key]
        // 检测特定类型参数
        if (item.inputType && this.checkType(options, value, item, !item.isRequired) == false) {
          return false
        }
        // 判断是否必填 或者 隐藏
        if (!item.isRequired || item.isHidden) continue;
        const showNote = isShowToast ? (item.title + "不能为空") : ""
        if (isTool.isHaveValue(value, showNote).isResult === false) {
          if (isThrow) throw new Error(showNote);
          return false
        }
      }
      return true
    },

    checkType(options, value, item, isCanNull = false) {
      let {
        isShowToast,
        isThrow
      } = options
      let showNote = isShowToast ? (item.title + "不能为空") : ""
      switch (item.inputType) {
        case "phone": // 手机
          if (isTool.isPhone(value, showNote, "手机号格式不正确", isCanNull).isResult === false) {
            if (isThrow) throw new Error(showNote);
            return false
          }
          break
        case "price": //价格
          if (isTool.isPrice(value, showNote, "价格格式不正确,保留两位小数", isCanNull).isResult === false) {
            if (isThrow) throw new Error(showNote);
            return false
          }
          break
        case "isNumber": //数字
          if (isTool.isNumber(value, showNote, "数值格式不正确", isCanNull).isResult === false) {
            if (isThrow) throw new Error(showNote);
            return false
          }
          break
      }
      return true
    },
    clickDeleteImage(e) {
      const {
        fileList,
        detail
      } = this.data
      const {
        key
      } = e.currentTarget.dataset
      const {
        index
      } = e.detail
      if (detail[key] && detail[key].map) {
        detail[key].splice(index, 1)
      } else {
        delete detail[key]
      }
      this.setData({
        detail
      })
      this.updateParentTargetDetail(key, detail[key])
    },
    // 文件超出大小限制
    oversize(e) {
      let {
        maxSize,
      } = e.currentTarget.dataset;
      // 默认最大1G, 超过1G需要自定义
      if (!maxSize) maxSize = 1073741824


      if (maxSize >= 1048576) {
        maxSize = Math.round(maxSize / 1024 / 1024) + "MB"
      } else if (maxSize >= 1024) {
        maxSize = Math.round(maxSize / 1024) + "KB"
      }
      wx.showToast({
        icon: "none",
        title: '文件超出' + maxSize + '大小限制',
      })
    },

    setIsShowRadioPicker(key, value) {
      const isShowRadioPicker = this.data.isShowRadioPicker
      isShowRadioPicker[key] = value
      this.setData({
        isShowRadioPicker
      })
    },
    // 展示picker
    clickShowPicker(e) {
      let {
        key
      } = e.currentTarget.dataset
      this.setIsShowRadioPicker(key, true)
    },
    clickCancelRadioPicker(e) {
      let {
        key
      } = e.currentTarget.dataset
      this.setIsShowRadioPicker(key, false)

    },
    clickSumbitRadioPicker(e) {
      const selectedItems = e.detail.selectedItems
      let {
        key
      } = e.currentTarget.dataset
      // 更新父界面的详情对象属性
      this.updateParentTargetDetail(key, selectedItems)
      const {
        detail
      } = this.data
      detail[key] = selectedItems
      this.setData({
        detail
      })
      this.setIsShowRadioPicker(key, false)
    },
    clickDeleted(e) {
      let {
        index,
        key
      } = e.currentTarget.dataset
      const {
        detail
      } = this.data
      const selectedItems = detail[key]
      selectedItems.splice(index, 1)
      this.setData({
        detail
      })
      // 更新父界面的详情对象属性
      this.updateParentTargetDetail(key, selectedItems)
    },
  }
})